<?php
@session_start();

//swift
require_once("libs/swift/swift_required.php");
//require_once("libs/Mijireh/Mijireh.php");
require_once("paypal/paypal.class.php");
require_once("libs/general_inc.php");

class Thankyou extends Controller {

    function __construct() {
        parent::__construct();
    }

    function index() {
        // echo 'in';exit;
        $sql = new sql();
        $sql->connect();
        $GETID = getId();
		$GENOBJ = new generalFunction();
        $paymentArray = $_SESSION['paymentArray'];
        if (array_key_exists('1', getId()) && isset($_SESSION['shoping_cart'])) {
            
            $GETID = getId();
            //$user_id = $GETID[1];
            $payment_type = $GETID[1];
            //$payment_optn = $GETID[3];
            $agent_id = $GETID[2];
            
            //$UserArray = $sql->fetch("tbl_user", array("user_id" => $user_id));
            $UserArray = $_SESSION['CHECKOUT_DATA'];
            $sessionArray = $_SESSION['CHECKOUT_DATA'];
            
            $last_quickbook_id = $_SESSION['CHECKOUT_DATA']['qb_customer_id'];
            
            $user_firstname = $UserArray['user_firstname'];
            $user_email = $UserArray['user_email'];
            $total_Amount = 0;
            $Discount_price = 0;
            $coupon_category = 0;
            $Discount_code = '';
            $cat_match_count = 1;
            $cat_match_qty = 1;
            $coupon_product = '';



            if (isset($_SESSION['coupon_detail'])) {
                $Discount_price = $_SESSION['coupon_detail']['coupon_price'];
                $Discount_code = $_SESSION['coupon_detail']['coupon_code'];
                if ($_SESSION['coupon_detail']['coupon_applied'] == 'per_item') {
                    $cat_match_count = 0;
                    $cat_match_qty = 0;
                    $coupon_category = $_SESSION['coupon_detail']['coupon_category'];
                    $coupon_product = $_SESSION['coupon_detail']['coupon_product'];
                }
            }
            foreach ($_SESSION['shoping_cart'] as $key => $value) {
                $total_Amount = $total_Amount + ($value['prd_qty'] * $value['prd_price']);
                if ($value['prd_cat_id'] == $coupon_category) {
                    $cat_match_count += 1;
                    $cat_match_qty += $value['prd_qty'];
                }
                if ($value['prd_id'] == $coupon_product) {
                    $cat_match_count +=1;
                    $cat_match_qty += $value['prd_qty'];
                }
            }


            $Final_amount_with_discount = $total_Amount - ($Discount_price * $cat_match_qty);

            $pt_type = "";
            $quickbook_ref_id = 0;


            if ($payment_type == 'paypal') {


                if (isset($_GET["token"]) && isset($_GET["PayerID"])) {
                    $token = $_GET["token"];
                    $payer_id = $_GET["PayerID"];


                    $total_Amount_pay = '';
                    $ItemName = '';
                    $ItemPrice = '';
                    $ItemDesc = '';
                    $ItemQty = '';
                    $ItemTotalPrice = '';
                    $i = 1;
                    $parmsString = '';
                    $j = 0;
                    foreach ($_SESSION['shoping_cart'] as $s_key => $s_value) {
                        $total_Amount_pay += $s_value['prd_qty'] * $s_value['prd_price'];
                        $ItemName = $s_value['prd_name'];
                        $ItemPrice = $s_value['prd_price'];
                        $ItemDesc = $s_value['prd_desc'];
                        $ItemQty = $s_value['prd_qty'];
                        $ItemTotalPrice = $ItemPrice * $ItemQty;
                        $parmsString .= '&L_PAYMENTREQUEST_0_NAME' . $j . '=' . urlencode($ItemName) .
                                //'&L_PAYMENTREQUEST_0_DESC'.$j.'=' . urlencode($ItemDesc) .
                                '&L_PAYMENTREQUEST_0_AMT' . $j . '=' . urlencode($ItemPrice) .
                                '&L_PAYMENTREQUEST_0_QTY' . $j . '=' . urlencode($ItemQty);
                        $j++;
                        $i++;
                    }






                    $discountString = '';
                    $no_discount_code = $j;
                    $discountTotalPrice = 0;

                    if (isset($_SESSION['coupon_detail'])) {
                        $discountName = "Discount Code - " . $_SESSION['coupon_detail']['coupon_code'];
                        $discountPrice = "-" . $_SESSION['coupon_detail']['coupon_price']; //Item Price
                        $discountDescription = $_SESSION['coupon_detail']['coupon_code'];
                        $discountQty = $cat_match_qty; // Item Quantity
                        $discountTotalPrice = $discountPrice * $discountQty;
                        $discountString .= '&L_PAYMENTREQUEST_0_NAME' . $no_discount_code . '=' . urlencode($discountName) .
                                //'&L_PAYMENTREQUEST_0_DESC'.$no_discount_code.'=' . urlencode($discountDescription) .
                                '&L_PAYMENTREQUEST_0_AMT' . $no_discount_code . '=' . urlencode($discountPrice) .
                                '&L_PAYMENTREQUEST_0_QTY' . $no_discount_code . '=' . urlencode($discountQty);
                    }
                    $GrandTotal = $total_Amount_pay + $discountTotalPrice;
					#$GrandTotal = 0;
                    $padata = '&TOKEN=' . urlencode($token) .
                            '&PAYERID=' . urlencode($payer_id) .
                            '&PAYMENTREQUEST_0_PAYMENTACTION=' . urlencode("SALE") .
                            $parmsString .
                            //Discount 
                            $discountString .
                            '&PAYMENTREQUEST_0_AMT=' . urlencode($GrandTotal);



                    //We need to execute the "DoExpressCheckoutPayment" at this point to Receive payment from user.
                    $paypal = new MyPayPal();
                    $httpParsedResponseAr = $paypal->PPHttpPost('DoExpressCheckoutPayment', $padata, PAYPAL_API_USERNAME, PAYPAL_API_PASSWORD, PAYPAL_API_SIGNATURE, PAYPAL_MODE);

					
					
                    if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {

                        $padata = '&TOKEN=' . urlencode($token);
                        $paypal = new MyPayPal();
                        $httpParsedResponseAr = $paypal->PPHttpPost('GetExpressCheckoutDetails', $padata, PAYPAL_API_USERNAME, PAYPAL_API_PASSWORD, PAYPAL_API_SIGNATURE, PAYPAL_MODE);


                        if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
                            $orderNum = $httpParsedResponseAr['PAYMENTREQUEST_0_TRANSACTIONID'];
                            $transaction_id = "Paypal - " . $orderNum;

                            if ($Discount_code != '') {
                                // $cat_match_count = 1; 
                                $lastcouponquery = "select * from tbl_coupon where cp_code ='" . $Discount_code . "' ";
                                $lastCoupon = $sql->SimpleQuery($lastcouponquery);
                                $coupon_used_count = $lastCoupon[0]['cp_used_count'] + 1;
                                $update = $sql->update('tbl_coupon', array("cp_used_count" => $coupon_used_count), array("cp_id" => $lastCoupon[0]['cp_id']));
                            }
                            $paymentdata = array(
                                "pt_type" => 'paypal',
                                "pt_store" => $pt_type,
                                //"pt_user_id" => $user_id,
                                "pt_coupon_code" => $Discount_code,
                                "pt_coupon_price" => $Discount_price,
                                "pt_coupon_qty" => $cat_match_qty,
                                "pt_amt_without_cp" => $total_Amount,
                                "pt_transaction_id" => $orderNum,
                                "pt_agent_id" => $agent_id,
                                "pt_total_amount" => $Final_amount_with_discount,
                                "pt_createDate" => date('Y-m-d h:i:s'),
                                "pt_status" => 'active',
                            );
							$filterArray = Array("TrimElement", "htmlEntity");  
                            $filterElements = $GENOBJ->filter($paymentdata, $filterArray);
                
                            $sql->insert('payment_order', $filterElements);
                          //  $sql->insert('payment_order', $paymentdata);
                            $lastpaymentid = $sql->last_id();


                            $responsedata = array(
                                "pr_pt_id" => $lastpaymentid,
                                "pr_response" => serialize($httpParsedResponseAr),
                                "pr_createdate" => date('Y-m-d h:i:s'),
                                "pr_status" => 'active',
                            );
                            $filterElements_responsedata = $GENOBJ->filter($responsedata, $filterArray);
                            $sql->insert('tbl_payment_response', $filterElements_responsedata);




                            foreach ($_SESSION['shoping_cart'] as $key => $value) {
                                $orderdata = array(
                                    //"or_user_id" => $user_id,
                                    "or_product_id" => $value['prd_id'],
                                    "payment_ref_id" => $lastpaymentid,
                                    "or_prd_qty" => $value['prd_qty'],
                                    "or_prd_price" => $value['prd_price'],
                                    "or_price" => $value['prd_qty'] * $value['prd_price'],
                                    "or_createdate" => date('Y-m-d h:i:s'),
                                    "or_status" => 1,
                                );
                                $filterElements_order = $GENOBJ->filter($orderdata, $filterArray);
                                $insert_order = $sql->insert('tbl_order', $filterElements_order);
                                $keyArray = $sql->fetch("tbl_metadata", array("mtd_key" => 'payment_key'));
                                $key = $keyArray['mtd_value'];

                                if ($key == count($paymentArray)) {
                                    $updatedKey = 1;
                                } else {
                                    $updatedKey = $key + 1;
                                }

                                $update = $sql->update('tbl_metadata', array("mtd_value" => $updatedKey), array("mtd_key" => 'payment_key'));
                            }
                            include('quickbooks/salerecepit.php');
                        }
                    } else {
					$_SESSION['PAYMENT_ERROR'][$payment_option]['CODE'] = $httpParsedResponseAr["L_ERRORCODE1"];
						
					$_SESSION['PAYMENT_ERROR'][$payment_option]['MESSAGE'] = urldecode($httpParsedResponseAr["L_LONGMESSAGE1"]);
						
                        header("Location: " . URL . "payment_error/");
                    }
                } else {
                    //errorURL .
					$_SESSION['PAYMENT_ERROR'][$payment_option]['CODE'] = $httpParsedResponseAr["L_ERRORCODE1"];
						
						$_SESSION['PAYMENT_ERROR'][$payment_option]['MESSAGE'] = urldecode($httpParsedResponseAr["L_LONGMESSAGE1"]);
						
                    header("Location: " . URL . "payment_error/");
                }
            }



            
           


        } 
        
        else {
           
            $GETID = getId();
            $payment_Ref_id = $GETID[1];
            $query = "select * from tbl_order od 
			join tbl_product as prd ON prd.prd_id = od.or_product_id 
			join payment_order as pt ON pt.pt_id = od.payment_ref_id 
			and payment_ref_id = '" . $payment_Ref_id . "'";
            $AllorderArray = $sql->SimpleQuery($query);
            
            $sessionArray = $_SESSION['CHECKOUT_DATA'];
            
            
            ob_start();
            include_once('mail/mail_recepit.php');
            $output = ob_get_contents();
            ob_end_clean();
            // Create the mail transport configuration
            $transport = Swift_MailTransport::newInstance();
            $mailMessage = Swift_Message::newInstance()
                    ->setSubject('TechOak Sales Receipt')
                    ->setFrom(array(ADMIN_EMAIL => ADMIN_NAME))
                    ->setTo(
                            array(
                                $sessionArray['user_email'] => $sessionArray['user_prefix'] . " " . $sessionArray['user_firstname'] . " " . $sessionArray['user_lastname'],
                            //$filterElements['email'] => $filterElements['name'] 
                    ))
                    //->setCc(array('support@techoak.com' => 'techoak'))
                    ->setCc(array('wikitudedeveloper@gmail.com' => 'techoak'))
                    ->setBody($output, 'text/html');
            // Send the email
            $mailer = Swift_Mailer::newInstance($transport);
            
			if(SALES_MAIL == true){
					$mailer->send($mailMessage);
			}
			
			
           
        }
        
        $this->view->sessionArray = $sessionArray;
        $this->view->allOrderArray = $AllorderArray;
        $this->view->render('thankyou');
    }

}